package main

import (
	"common"
	"common/log"
	"context"
	"errors"
	"euplink"
	"euplink/cmd/euplink/dir"
	"fmt"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"strings"
	"time"
)

var uploadDirCmd = &cobra.Command{
	Use:   "uploaddir",
	Short: "上传指定文件夹录像",
	Long:  "euplink uploaddir (dir)",
	RunE:  cmdUploadDir,
}

func cmdUploadDir(cmd *cobra.Command, args []string) error {
	rootDir := "/data_dir/video/live/"
	if len(args) == 1 {
		rootDir = args[0]
	}
	if len(args) >= 1 {
		//return errors.New("参数错误")
		rootDir = args[0]
	}
	exist, _ := dir.FileExists(rootDir)
	if !exist {
		return errors.New("参数错误,目录不存在")
	}
	n := len(rootDir)
	if rootDir[n-1] != '/' {
		rootDir += "/"
	}

	fmt.Println("rootDir", rootDir)

	ctx := context.Background()
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(ctx)
	defer cancel()
	zapLog := log.NewZapLog(&runConfig.Log)

	prj, err := euplink.NewProject(ctx, runConfig.Project, zapLog)
	if err != nil {
		return fmt.Errorf("project init err: %s", err)
	}
	ch := make(chan string, 10)

	prj.StartUpdateNodeServer(ctx)
	startListenDir(ctx, ch, rootDir) //监听指定目录
	for {
		select {
		case ts := <-ch:
			fmt.Println("#", ts)
			uploadOneTs(prj, rootDir, ts, zapLog)
		case <-ctx.Done():
			fmt.Println("done")
			break
		}
	}
}

func startListenDir(ctx context.Context, ch chan string, folder string) {
	//const folder = "/data_dir/video/live/"
	ids := dir.GetIPCIds(folder)
	fmt.Println("StartListenFiles", ids)
	for _, id := range ids {
		listen := dir.NewFolderListen(folder, id)
		go listen.Run(ctx, ch)
	}
}
func uploadOneTs(proj *euplink.Project, folder, file string, log *zap.Logger) {
	var key = ""
	if strings.HasPrefix(file, folder) {
		key = file[len(folder):]
	}
	if len(key) == 0 {
		return
	}
	ctx2 := context.Background()
	fp, size, err := common.OpenFile(file)
	if err != nil {
		log.Error("## 失败:", zap.String("", file), zap.Error(err))
		return
	}
	err = proj.UploadObject(ctx2, "default", key, fp, false, size, nil)
	if err != nil {
		log.Error("## 失败:", zap.String("", file), zap.Error(err))
		time.Sleep(time.Second * 1)
	}
	log.Info("## 成功:", zap.String("", file))
}
